import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rider/event/click_manger_pop_event.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/utils/toast.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/change_stations_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/status_utils.dart';
import 'package:flutter_rider/main/widgets/ext/u_shape.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/pop/pop_car_status.dart';
import 'package:flutter_rider/main/widgets/state/refreshable_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/module/car/models/manage_model.dart';

class ManagePage extends StatefulWidget {
  const ManagePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return ManagePageState();
  }
}

class ManagePageState extends State<ManagePage> {
  final _stateController = RefreshableLayoutController();
  late StreamSubscription _eventFn1;
  late StreamSubscription _eventFn2;
  final List _tabs = ["全部", "任务中", "空闲中", "调配中", "不可用"];
  //被选中车辆的模型
  late ManageModel _selectData;
  int _index = 0;
  int _carStatus = 0;

  @override
  void initState() {
    super.initState();

    _stateController.reload();

    //这里是给调车成功之后再弹出一个框，看下这辆车的状态
    _eventFn1 = eventBus.on<ChangeStationsEvent>().listen((event) {
      OpenUtils.pop2(
          context,
          PopCarStatus(_selectData.id, PopEnterType.carManage,
              title: _selectData.car_no));
      _stateController.reload();
    });
    //这里是调车选站点返回之后需要弹出来的框
    _eventFn2 = eventBus.on<ClickMangerPopCarEvent>().listen((event) {
      OpenUtils.pop2(
          context,
          PopCarStatus(_selectData.id, PopEnterType.carManage,
              title: _selectData.car_no));
    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn1.cancel();
    _eventFn2.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: UIColor.color_main,
      child: Column(
        children: [
          _renderTitle(),
          Container(height: 0.5, color: Colors.black12),
          _renderTab(),
          _renderList()
        ],
      ),
    );
  }

  Widget _renderTitle() {
    return Container(
      color: UIColor.color_content,
      width: double.infinity,
      height: MediaQuery.of(context).padding.top + 44.rpx,
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child:
          UText.get("车辆管理", Colors.black, 16.rpx, fw: FontWeight.w600).center,
    );
  }

  Widget _renderTab() {
    return Container(
      decoration: BoxDecoration(
        color: UIColor.color_content,
        border: Border.all(width: 1.rpx, color: const Color(0xffF6F6F6)),
      ),
      child: Row(
        children: _tabs.asMap().keys.map((e) => _renderTabItem(e)).toList(),
      ),
    );
  }

  Widget _renderTabItem(int index) {
    var color =
        _index == index ? UIColor.color_primary : Colors.black.withOpacity(0.6);
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          setState(() {
            _index = index;
            _stateController.reload();
          });
        },
        child: Column(
          children: [
            12.hspace,
            UText.get(_tabs[index], color, 16.rpx, fw: FontWeight.w600),
            3.hspace,
            Container(
              width: 24.rpx,
              height: 4.rpx,
              decoration: BoxDecoration(
                color: _index == index
                    ? UIColor.color_primary
                    : Colors.transparent,
                borderRadius: BorderRadius.all(Radius.circular(3.rpx)),
              ),
            ),
            3.hspace,
          ],
        ),
      ),
    );
  }

  Widget _renderList() {
    return Expanded(
        child: RefreshableLayout(
            controller: _stateController,
            urlCallback: _buildUrl,
            itemBuilder: _renderListItem));
  }

  String _buildUrl() {
    if (_index == 0) {
      _carStatus = 0;
    } else if (_index == 1) {
      _carStatus = 3;
    } else if (_index == 2) {
      _carStatus = 2;
    } else if (_index == 3) {
      _carStatus = 4;
    } else if (_index == 4) {
      _carStatus = -1;
    }
    var baseUrl = "/car/list?status=$_carStatus";
    return baseUrl;
  }

  Widget _renderListItem(dynamic data, int index) {
    var manageModel = ManageModel.fromMap(data);
    int _width = (manageModel.electricity / 4).round();
    return GestureDetector(
      onTap: () {
        _selectData = manageModel;
        OpenUtils.pop2(
            context,
            PopCarStatus(manageModel.id, PopEnterType.carManage,
                title: manageModel.car_no));
      },
      child: Container(
        decoration: BoxDecoration(
          color: UIColor.color_content,
          borderRadius: BorderRadius.circular(12.rpx),
        ),
        margin: EdgeInsets.only(left: 12.rpx, right: 12.rpx, top: 10.rpx),
        padding: EdgeInsets.all(16.rpx),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                UText.getSubText("ID: ${manageModel.car_id}").expand,
                Row(
                  children: [
                    Stack(
                      children: [
                        Container(
                            width: 29.rpx,
                            height: 12.rpx,
                            alignment: Alignment.centerLeft,
                            decoration: const BoxDecoration(
                              image: DecorationImage(
                                image:
                                    AssetImage('assets/image/poi/electric.png'),
                                fit: BoxFit.fill, // 完全填充
                              ),
                            ),
                            child: Container(
                              width: _width.rpx,
                              height: 10.rpx,
                              margin: EdgeInsets.only(left: 1.rpx),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(2.rpx),
                                color: manageModel.electricity > 50
                                    ? UIColor.color_t6
                                    : manageModel.electricity < 20
                                        ? UIColor.color_none
                                        : UIColor.color_work,
                              ),
                            )),
                      ],
                    ),
                    4.wspace,
                    UText.get("${manageModel.electricity}%", UIColor.color_t1,
                        14.rpx),
                  ],
                )
              ],
            ),
            12.hspace,
            _renderSecond(manageModel),
            12.hspace,
            _renderCarStatus(manageModel),
            8.hspace,
            Row(
              children: [
                UText.get("车辆类型", UIColor.color_t3, 14.rpx),
                8.wspace,
                UText.get(manageModel.brand, UIColor.color_t1, 14.rpx).expand,
                UShape.getCircle(
                    size: 10.rpx,
                    color: manageModel.status == -1
                        ? const Color(0xffE34D59)
                        : const Color(0xff00A870)),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _renderCarStatus(ManageModel data) {
    Color color = UIColor.color_none;
    var text = "不可用";
    if (data.status == 2 || data.status == 5) {
      color = UIColor.color_wait;
      text = "空闲中";
    } else if (data.status == 3) {
      color = UIColor.color_work;
      text = "任务中";
    } else if (data.status == 4) {
      color = UIColor.color_dispatch;
      text = "调配中";
    }
    return Row(
      children: [
        UText.get("派单方式", UIColor.color_t3, 14.rpx),
        8.wspace,
        UText.get(StatusUtils.getOrderMode(data.mode) + "派单", UIColor.color_t1,
            14.rpx),
        40.wspace,
        UText.get("任务状态", UIColor.color_t3, 14.rpx),
        8.wspace,
        UText.get(text, color, 14.rpx),
      ],
    );
  }

  Widget _renderSecond(ManageModel data) {
    Color color = UIColor.color_none;
    var carImg = R.image_car_malfunction;
    if (data.status == 2) {
      color = UIColor.color_wait;
      carImg = R.image_car_leisure;
    } else if (data.status == 3) {
      color = UIColor.color_work;
      carImg = R.image_car_working;
    } else if (data.status == 4) {
      color = UIColor.color_primary;
      carImg = R.image_car_dispatch;
    }
    return Row(
      children: [
        Container(
          width: 32.rpx,
          height: 32.rpx,
          decoration: const BoxDecoration(
            color: Color(0xffeeeeee),
            shape: BoxShape.circle,
          ),
          padding: EdgeInsets.symmetric(horizontal: 4.rpx, vertical: 4.rpx),
          child: SvgPicture.asset(carImg, width: 30.rpx, height: 15.rpx),
        ),
        16.wspace,
        Expanded(
          child: UText.get(data.car_no, UIColor.color_t1, 20.rpx),
        ),
        4.wspace,
        CupertinoSwitch(
            value: data.car_status == 1,
            activeColor: UIColor.color_primary,
            onChanged: (value) {
              _onClickSwitch(data, value);
            }),
      ],
    );
  }

  _onClickSwitch(ManageModel model, bool value) {
    CustomAlertDialog.showConfirmDialog(context,
        title: "${value ? '开启' : '停用'}车辆",
        content: "确认${value ? '开启' : '停用'}车辆  ${model.car_no}  吗？",
        confirmText: '${value ? '开启' : '停用'}车辆', onConfirm: () {
      var json = {};
      json["id"] = model.id;
      json["car_status"] = value ? 1 : -1;
      // Tip.show(model.id.toString() + "---" + model.car_no);
      Api.submitx(context, "/car/is_exec", data: json, success: (res) {
        _stateController.reload();
        Toast.show(context, msg: "${value ? '开启' : '停用'}成功", seconds: 2);
      },
          fail: (res) {},
          //successTip: "操作成功",
          failTip: "操作失败");
    });
  }
}
